<template>
  <div>
    <div class="self-box">
      <Card class="warp-card">
        <!-------操作按钮行 begin------->
        <Row class="marginBottom10">
          <Form :model="searchForm" class="tools" inline ref="searchForm">
            <FormItem>
                  <DatePicker v-model="searchForm.startTime" @on-change="getStartTime"
                  format="yyyy-MM-dd"
                  type="date" placeholder="Start Time"
                  style="width: 200px"></DatePicker>
                  -
                  <DatePicker  v-model="searchForm.endTime" @on-change="getEndTime"
                  format="yyyy-MM-dd"
                  type="date" placeholder="End Time"
                  style="width: 200px"></DatePicker>
            </FormItem>
            <FormItem>
              <ButtonGroup>
                <Button
                  @click="find"
                  icon="ios-search"
                  type="primary"
                  v-privilege="'filemapping-list-query'"
                  >Search</Button
                >
              </ButtonGroup>
            </FormItem>
          </Form>
          <div class="operateBtn">
          <Upload
            :action="uploadUrl"
            :headers="uploadHeader"
            :onError="uploadError"
            :onSuccess="uploadSuccess"
            :showUploadList="false"
          >
            <Button
              size="small"
              class="marginLeft10"
              type="primary"
              v-privilege="'filemapping-template-upload'"
              >Upload Mapping File</Button
            >
          </Upload>
          <Button
            @click="downloadFile"
            type="primary"
            class="marginLeft10"
            size="small"
            v-privilege="'filemapping-template-download'"
            >Download</Button
          >
          <Button
            @click="deleteFile"
            class="marginLeft10"
            icon="ios-trash-outline"
            size="small"
            type="error"
            v-privilege="'filemapping-template-delete'"
            >Delete</Button
          >
          </div>
        </Row>
        <Table
          :columns="columns"
          :data="tableData"
          border
          highlight-row
          ref="mainTable"
          @on-selection-change="selectChange"
        ></Table>
        <Page
          :current="searchForm.pageNum"
          :page-size="searchForm.pageSize"
          :page-size-opts="[10, 20, 30, 50, 100]"
          :total="total"
          @on-change="changePage"
          @on-page-size-change="changePageSize"
          show-elevator
          show-sizer
          show-total
          class="smart-query-table-page"
        ></Page>
      </Card>
    </div>
    <Modal
      :footer-hide="true"
      title="Upload"
      v-model="upload.show"
      @on-cancel="uploadClose"
      width="500"
    >
      <UploadFile
        :parentFolderId='currentFileID'
        @on-form-close="uploadClose"
      />
    </Modal>
  </div>
</template>

<script>
import { dateTimeRangeConvert } from '@/lib/util';
import { fileApi } from '@/api/file.js';
import UploadFile from '@/components/uploadFile/index';
import Cookies from 'js-cookie';
import { TOKEN_KEY } from '@/lib/cookie';

export default {
  name: 'FileMappingList',
  components: {
    UploadFile
  },
  props: {},
  data () {
    return {
      saveModal: {
        show: false,
        isUpdate: false,
        updateData: null
      },
      fileModal: {
        show: false,
        isUpdate: false,
        updateData: null
      },
      resetModal: {
        show: false,
        isUpdate: false,
        updateData: null
      },
      batchDeleteModal: {
        show: false
      },
      upload: {
        show: false
      },
      // 数据量
      total: null,
      // 查询参数
      searchForm: {
        endTime: '',
        pageNum: 1,
        pageSize: 10,
        searchCount: true,
        parentFolderId: 1,
        startTime: ''
      },
      currentid: 0,
      currentFileID: 1,
      selectFolderObject: [],
      // 表头
      columns: [
        {
          type: 'selection',
          width: 30,
          align: 'center'
        },
        {
          title: 'Mapping File',
          key: 'mappingFileName'
        },
        {
          title: 'Creation Time',
          key: 'createTime'
        },
        {
          title: 'Mapping Result',
          key: 'mappingStatus'
        },

        {
          title: 'User',
          key: 'createByName'
        }

      ],
      // table数据
      tableData: [],
      // 删除id
      delId: null,
      mainTableSelectArray: []

    };
  },
  computed: {
    uploadHeader: function () {
      let header = {
        'x-access-token': Cookies.get(TOKEN_KEY)
      };
      return header;
    },
    uploadUrl: function () {
      let baseUrl = fileApi.fileMappingUploadLocalUrl;
      return baseUrl;
    }
  },
  watch: {},
  filters: {},
  mounted () {
    this.queryList();
  },
  created () {
    this.folderObjList = [];
    // this.breadArr = this.getParentId(this.data2, 3).reverse();
  },
  methods: {
    async downloadFile () {
      if (!this.selectMessage()) return;
      let arr = [];
      this.selectFolderObject.forEach(item => {
        let obj = {
          fileMode: 0,
          id: item.fileId
        };
        arr.push(obj);
      });
      fileApi.downTemp({ fileModeList: arr });
    },
    downloadFile1 (data) {
      let blob = new Blob([data], { type: 'application/zip' });
      let url = window.URL.createObjectURL(blob);
      const link = document.createElement('a'); // 创建a标签
      link.href = url;
      link.download = 'fileDown111'; // 重命名文件
      link.click();
      URL.revokeObjectURL(url); // 释放内存
    },
    getStartTime (startTime) {
      this.searchForm.startTime = startTime;
    },
    getEndTime (endTime) {
      this.searchForm.endTime = endTime;
    },
    // 删除确定
    async deleteSure (data) {
      this.$Spin.show();
      let ids = [];
      data.forEach(item => {
        let obj = {
          fileId: item.id,
          fileMode: item.fileMode
        };
        ids.push(item.id);
      });
      let res = await fileApi.deleteM({ idArray: ids });
      this.$Message.success('删除成功');
      this.$Spin.hide();
      this.find();
    },
    // 删除操作
    deleteFile () {
      if (!this.selectMessage()) return;
      this.$Modal.confirm({
        title: '友情提醒',
        content: '确定要删除吗？',
        onOk: () => {
          this.deleteSure(this.selectFolderObject);
        }
      });
    },
    // 查询
    find () {
      this.searchForm.pageNum = 1;
      this.searchForm.pageSize = 10;
      this.queryList();
    },
    // 更改分页查询条数
    changePageSize (pageSize) {
      this.searchForm.pageNum = 1;
      this.searchForm.pageSize = pageSize;
      this.queryList();
    },
    // 获取邮件数据
    async queryList () {
      this.$Spin.show();
      // 开始时间，结束时间
      let res = await fileApi.queryM(this.searchForm);
      this.$Spin.hide();
      this.tableData = res.data.list;
      this.total = res.data.total;
      if (res.data.pages < this.searchForm.pageNum) {
        this.searchForm.pageNum = res.data.pages;
      }
    },

    // 页码改变
    changePage (pageNum) {
      this.searchForm.pageNum = pageNum;
      this.queryList();
    },
    showAddPeonyForm () {
      if (!this.selectMessage()) return;
      this.saveModal.isUpdate = false;
      this.saveModal.show = true;
    },
    showEditPeonyForm (updateObject) {
      this.saveModal.isUpdate = true;
      this.saveModal.updateData = updateObject;
      this.saveModal.show = true;
    },
    saveFormClose () {
      this.saveModal.show = false;
      this.queryList();
    },
    uploadClose () {
      this.upload.show = false;
      this.queryList();
    },
    showAddFileForm () {
      this.fileModal.isUpdate = false;
      this.fileModal.show = true;
    },
    showEditFileForm (updateObject) {
      this.fileModal.isUpdate = true;
      this.fileModal.updateData = updateObject;
      this.fileModal.show = true;
    },
    fileFormClose () {
      this.fileModal.show = false;
    },
    showResetFileForm () {
      if (!this.selectMessage()) return;
      this.resetModal.isUpdate = true;
      this.resetModal.updateData = this.selectFolderObject[0];
      this.resetModal.show = true;
    },
    selectMessage () {
      if (this.selectFolderObject.length === 0) {
        this.$Message.warning('请选择要操作的文件夹或文件');
        return false;
      }
      return true;
    },
    newFileForm () {
      this.resetModal.isUpdate = false;
      this.resetModal.updateData = null;
      this.resetModal.show = true;
    },
    showResetEditFileForm (updateObject) {
      this.resetModal.isUpdate = true;
      this.resetModal.updateData = updateObject;
      this.resetModal.show = true;
    },
    resetFormClose () {
      this.resetModal.show = false;
      this.queryList();
    },
    // 校验是否有选中
    validateMainTableSelection () {
      this.mainTableSelectArray = this.$refs.mainTable.getSelection();
      if (this.mainTableSelectArray.length < 1) {
        this.$Message.error('请选择至少一条数据');
        return false;
      }
      return true;
    },
    // 上传成功钩子
    uploadSuccess (e) {
      if (!e.success) {
        return this.uploadError(e);
      }
      this.$Spin.hide();
      this.$Message.success('上传成功');
      this.find();
    },
    // 上传失败钩子
    uploadError (e) {
      console.log(e);
      if (e.msg) {
        this.$Message.error({
          type: 'error',
          content: e.msg,
          closable: true,
          duration: 10 });
      } else {
        this.$Message.error('上传出错，请重试！');
      }
      this.find();
    },
    // 上传成功钩子
    async uploadSuccessSingle (e) {
      if (!e.success) {
        console.error(e);
        return this.uploadErrorSingle();
      }
      this.$Spin.show();
      let reqBody = {
        moduleId: 1,
        moduleType: this.searchForm.moduleType ? this.searchForm.moduleType : 1,
        fileLocationType: this.searchForm.fileLocationType
          ? this.searchForm.fileLocationType
          : 1,
        fileName: e.data.fileName,
        filePath: e.data.filePath
      };
      let rep = await fileApi.addFile(reqBody);
      this.$Spin.hide();
      this.$Message.success('上传成功');
      this.find();
    },
    // 上传失败钩子
    uploadErrorSingle (e) {
      this.$Message.error('上传出错，请重试！');
      console.error(e);
      this.find();
    },
    // 单机行
    selectTable (item) {
      console.log(item, 12345);
    },
    selectChange (data) {
      this.selectFolderObject = data;
    },
    // 查询文件夹下的文件
    selectChild () {
      this.currentFileID = this.currentFolder.id;
      this.searchForm.parentFolderId = this.currentFolder.id;
      this.childFile();
    },
    // 从文件目录中选中文件加
    selectFolderByPath (data, index) {
      if (index === 0) {
        this.folderObjList = [];
      } else {
        this.folderObjList = this.folderObjList.slice(0, index);
      }
      this.selectFolder(data);
    },
    selectFolder (data) {
      this.currentFolder = data;
      // 判断当前是否是文件夹，如果文件夹
      if (data.fileMode == 1) {
        // 点击文件夹查询
        this.folderObjList.push(data);
        this.currentFileID = this.currentFolder.id;
        this.searchForm.parentFolderId = this.currentFolder.id;
        this.childFile();
      } else {
        // 点击文件展示文件详情
      }
    },
    async childFile () {
      this.$Spin.show();
      let searchForm = {
        // fileMode: 1,       //文件是普通文件 0  还是文件夹  1
        pageNum: 1,
        pageSize: 10,
        parentFolderId: this.currentFileID, // 初始化文件夹父节点为0
        searchCount: true // 是否查询总条数
      };
      let res = await fileApi.queryFileManageList(searchForm);
      this.$Spin.hide();
      this.tableData = res.data.list;
      // 获取文件夹列表
      // this.getCurrentFilePath();
      this.total = res.data.total;
      // 选择清空
      this.currentid = 0;
      this.selectFolderObject = [];
      if (res.data.pages < this.searchForm.pageNum) {
        this.searchForm.pageNum = res.data.pages;
      }
    },
    getParentId (list, id) {
      for (let i in list) {
        if (list[i].id === id) {
          return [list[i]];
        }
        if (list[i].children) {
          let node = this.getParentId(list[i].children, id);
          if (node !== undefined) {
            return node.concat(list[i]);
          }
        }
      }
    }
  }
};
</script>
<style lang="less" scoped>
.nav-file {
  height: 50px;
  display: flex;
  align-items: center;
}
.FolderDic{
  div{
    display:inline-block;
    height:25px;line-height:25px;
    font-size: 14px;
    font-weight: 600;
    color: #607d8b;
    margin-left:6px;
    cursor: pointer;
  }
}
.operateBtn{
  display: inline-block;
  position: absolute;
  right: 20px;
  top: 22px;
}
.breadCrumb {
  width: 100%;
  line-height: 40px;
  border-top: 1px solid @garyA300;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  .bread-li {
    margin-right: 10px;
    display: flex;
    align-items: center;
    .bread-title {
      margin-right: 10px;
      cursor: pointer;
      font-weight: bold;
      &:hover {
        opacity: 0.6;
      }
    }
  }
}
.operateBtn{
    /deep/ .ivu-upload{
    display: inline-block;
  }
}

</style>
